package face.pay.cpn.cpnmachinfo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import face.pay.AbstractRedis;
import face.pay.constant.CacheKey;
import face.pay.cpn.cpnmachinfo.ICpnMachInfoService;
import face.pay.cpn.param.CpnMchIfoResult;
import face.pay.dao.CpnMchInfoDao;
import face.pay.entity.CpnMchInfo;
import face.pay.entity.CpnWxAppInfo;
import face.pay.entity.UserInfo;
import face.pay.util.DateUtil;
import face.pay.util.HttpClientUtil;
import face.pay.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.api.API;
import weixin.popular.api.MediaAPI;
import weixin.popular.bean.media.Media;
import weixin.popular.bean.media.MediaGetResult;
import weixin.popular.bean.media.MediaType;
import weixin.popular.bean.media.UploadimgResult;
import weixin.popular.client.LocalHttpClient;

import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class CpnMachInfoServiceImpl implements ICpnMachInfoService {


    @Autowired
    private CpnMchInfoDao cpnMchInfoDao;


    @Autowired
    private AbstractRedis abstractRedis;


    /**
     * 查询卡券进件资料
     *
     * @param loginuser
     * @return
     */
    @Override
    public CpnMchInfo queryCpnMachInfo(UserInfo loginuser) {
        CpnMchInfo record = new CpnMchInfo();
        record.setUserId(loginuser.getId());
        CpnMchInfo cpnMchInfo = this.cpnMchInfoDao.queryCpnMchInfo(record);
        if (cpnMchInfo == null) {
            CpnMchInfo info = new CpnMchInfo();
            info.setUserId(loginuser.getId());
            info.setOemId(loginuser.getOemId());
            info.setCreatedBy(loginuser.getId());
            info.setUpdatedBy(loginuser.getId());
            this.cpnMchInfoDao.insert(info);
            return info;
        } else {
            return cpnMchInfo;
        }
    }


    /**
     * 获取token
     *
     * @return
     */
    private String getAccess_token() {
        String str = (String) this.abstractRedis.get(CacheKey.WX_APP_INFO);
        if (str == null) {
            return null;
        }
        CpnWxAppInfo cpnWxAppInfo = null;
        try {
            cpnWxAppInfo = JSONObject.parseObject(str, CpnWxAppInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return cpnWxAppInfo.getAccess_token();
    }

    /**
     * 上传logo
     *
     * @param fileBytes
     * @param originalFilename
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage logoUpload(byte[] fileBytes, String originalFilename, UserInfo loginUser) {
        //   获取access_token
        String access_token = getAccess_token();
        if (access_token == null || access_token.isEmpty()) {
            log.warn("上传logo userId:{} 获取access_token失败!!!!", loginUser.getId());
            return ResultMessage.createFail("请稍后再试!!!");
        }
        UploadimgResult result = MediaAPI.mediaUploadimg(access_token, new ByteArrayInputStream(fileBytes));
        if (result == null || StringUtils.isBlank(result.getUrl())) {
            log.warn("上传logo userId:{} 上传失败!!!!", loginUser.getId());
            return ResultMessage.createFail("上传失败请检查文件大小,或请稍后再试!!!");
        }
        CpnMchInfo info = new CpnMchInfo();
        info.setUserId(loginUser.getId());
        info.setLogo_url(result.getUrl());
        info.setUpdatedBy(loginUser.getId());
        this.cpnMchInfoDao.update(info);
        HashMap<String, String> map = new HashMap<>();
        map.put("logo_url", result.getUrl());
        return ResultMessage.createSuccess(map);
    }


    /**
     * 物料上传
     *
     * @param fileBytes
     * @param originalFilename
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage materialUpload(byte[] fileBytes, String originalFilename, String keyName, UserInfo loginUser) {
        //   获取access_token
        String access_token = getAccess_token();

        if (access_token == null || access_token.isEmpty()) {
            log.warn("上传物料 userId:{} 获取access_token失败!!!!", loginUser.getId());
            return ResultMessage.createFail("请稍后再试!!!");
        }

        Media media = MediaAPI.mediaUpload(access_token, MediaType.image, new ByteArrayInputStream(fileBytes));
        if (media == null || StringUtils.isBlank(media.getMedia_id())) {
            log.warn("上传物料 userId:{} 上传失败!!!!", loginUser.getId());
            return ResultMessage.createFail("上传失败请检查文件大小,或请稍后再试!!!");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put(keyName, media.getMedia_id());
        map.put("userId", loginUser.getId());
        this.cpnMchInfoDao.updateImg(map);

        HashMap<String, String> mediaMap = new HashMap<>();
        mediaMap.put("media_id", media.getMedia_id());
        return ResultMessage.createSuccess(mediaMap);
    }


    /**
     * 获取物料
     *
     * @param mediaId
     * @param loginUser
     * @return
     */
    @Override
    public byte[] getMedia(String mediaId, UserInfo loginUser) {
        //   获取access_token
        String access_token = getAccess_token();
        if (access_token == null || access_token.isEmpty()) {
            log.warn("获取物料 userId:{} 获取access_token失败!!!!", loginUser.getId());
            return new byte[0];
        }
        MediaGetResult mediaGetResult = MediaAPI.mediaGet(access_token, mediaId, false);
        if (mediaGetResult == null) {
            return new byte[0];
        }
        return mediaGetResult.getBytes();
    }

    /**
     * 获取卡券开放类目
     *
     * @param loginUser
     * @return
     */
    @Override
    public String getapplyprotocol(UserInfo loginUser) {
        String access_token = getAccess_token();
        String url = "https://api.weixin.qq.com/card/getapplyprotocol?access_token=" + access_token;
        String res = HttpClientUtil.doGet(url);
        return res;
    }

    /**
     * 暂存资料
     *
     * @param loginUser
     * @param cpnMchInfo
     * @return
     */
    @Override
    public ResultMessage update(UserInfo loginUser, CpnMchInfo cpnMchInfo) {
        //转换成秒
        String end_date = cpnMchInfo.getEnd_date();
        String pattern = "yyyy年MM月dd日";
        Date date = DateUtil.dateParse(end_date, pattern);
        cpnMchInfo.setEnd_time(date.getTime() / 1000);
        cpnMchInfo.setUpdatedBy(loginUser.getId());
        cpnMchInfo.setStatus(0);
        this.cpnMchInfoDao.update(cpnMchInfo);
        return ResultMessage.createSuccess();
    }


    /**
     * 提交进件
     *
     * @param loginUser
     * @param cpnMchInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage submit(UserInfo loginUser, CpnMchInfo cpnMchInfo) {

        //   获取access_token
        String access_token = getAccess_token();
        if (access_token == null || access_token.isEmpty()) {
            log.warn("提交子商户优惠券进件 userId:{} 获取access_token失败!!!!", loginUser.getId());
            return ResultMessage.createFail("稍后再试!!!!");
        }
        //查最新的数据
        CpnMchInfo record = new CpnMchInfo();
        record.setId(cpnMchInfo.getId());
        CpnMchInfo cpn = this.cpnMchInfoDao.queryCpnMchInfo(record);

        if (cpn.getMerchant_id() != null && cpn.getMerchant_id() > 0) {
            return ResultMessage.createFail("您已经进件,请不要重复提交进件!");
        }
        //组织参数
        HashMap<String, Object> praminfo = new HashMap<>();
        HashMap<String, Object> pramcpn = new HashMap<>();
        pramcpn.put("brand_name", cpn.getBrand_name());

        /*if (StringUtils.isNotBlank(cpn.getApp_id())) {
            pramcpn.put("app_id", cpn.getApp_id());
        }*/

        pramcpn.put("logo_url", cpn.getLogo_url());
        pramcpn.put("protocol", cpn.getProtocol());
        pramcpn.put("end_time", cpn.getEnd_time());
        pramcpn.put("primary_category_id", cpn.getPrimary_category_id());
        pramcpn.put("secondary_category_id", cpn.getSecondary_category_id());
        if (StringUtils.isNotBlank(cpn.getAgreement_media_id()) && StringUtils.isNotBlank(cpn.getOperator_media_id())) {
            pramcpn.put("agreement_media_id", cpn.getAgreement_media_id());
            pramcpn.put("operator_media_id", cpn.getOperator_media_id());
        }
        praminfo.put("info", pramcpn);
        log.info("优惠券进件提交到微信>>>>>>>>参数:{}", praminfo.toString());
        HttpUriRequest httpUriRequest = RequestBuilder
                .post()
                .setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()))
                .setUri("https://api.weixin.qq.com/card/submerchant/submit")
                .addParameter("access_token", API.accessToken(access_token))
                .setEntity(new StringEntity(JSON.toJSONString(praminfo), Charset.forName("utf-8")))
                .build();
        CpnMchIfoResult cpnMchIfoResult = LocalHttpClient.executeJsonResult(httpUriRequest, CpnMchIfoResult.class);
        log.info("优惠券进件提交到微信返回参数<<<<<<<:{}", cpnMchIfoResult.toString());

        if (!"0".equals(cpnMchIfoResult.getErrcode())) {
            log.warn("优惠券进件提交到微信接口调用失败!!!");
            return ResultMessage.createFail("优惠券进件系统繁忙请稍后检查资料后再试!!! errcode:"+cpnMchIfoResult.getErrcode()+"errmsg:"+cpnMchIfoResult.getErrmsg());
        }

        Map resInfo = JSON.parseObject(cpnMchIfoResult.getInfo());
        log.info(cpnMchIfoResult.getInfo());
        String merchant_id = String.valueOf(resInfo.get("merchant_id"));
        String status = String.valueOf(resInfo.get("status"));
        log.info("状态status :{}   merchant_id :{}", status, merchant_id);
        cpn.setMerchant_id(Integer.parseInt(merchant_id));
        if ("CHECKING".equalsIgnoreCase(status)) {
            cpn.setStatus(1);
            cpn.setReason("审核中");
        } else if ("APPROVED".equalsIgnoreCase(status)) {
            cpn.setStatus(2);
            cpn.setReason("已通过");
        } else if ("REJECTED".equalsIgnoreCase(status)) {
            cpn.setStatus(-1);
            cpn.setReason("被驳回");
        } else if ("EXPIRED".equalsIgnoreCase(status)) {
            cpn.setStatus(-1);
            cpn.setReason("协议已过期");
        }
        this.cpnMchInfoDao.update(cpn);
        return ResultMessage.createSuccess();
    }

    /**
     * 进件失败修改后提交进件资料
     *
     * @param loginUser
     * @param cpnMchInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage modifySubmit(UserInfo loginUser, CpnMchInfo cpnMchInfo) {
        //   获取access_token
        String access_token = getAccess_token();
        if (access_token == null || access_token.isEmpty()) {
            log.warn("提交子商户优惠券进件 userId:{} 获取access_token失败!!!!", loginUser.getId());
            return ResultMessage.createFail("稍后再试!!!!");
        }
        //查最新的数据
        CpnMchInfo record = new CpnMchInfo();
        record.setId(cpnMchInfo.getId());
        CpnMchInfo cpn = this.cpnMchInfoDao.queryCpnMchInfo(record);
        if (cpn.getMerchant_id() == null || cpn.getMerchant_id() == 0) {
            return ResultMessage.createFail("您还没有进过件,请直接提交进件!");
        }
        //组织参数
        HashMap<String, Object> praminfo = new HashMap<>();
        HashMap<String, Object> pramcpn = new HashMap<>();
        pramcpn.put("merchant_id", cpn.getMerchant_id());
        pramcpn.put("brand_name", cpn.getBrand_name());

        /*if (StringUtils.isNotBlank(cpn.getApp_id())) {
            pramcpn.put("app_id", cpn.getApp_id());
        }*/

        pramcpn.put("logo_url", cpn.getLogo_url());
        pramcpn.put("protocol", cpn.getProtocol());
        pramcpn.put("end_time", cpn.getEnd_time());
        pramcpn.put("primary_category_id", cpn.getPrimary_category_id());
        pramcpn.put("secondary_category_id", cpn.getSecondary_category_id());
        if (StringUtils.isNotBlank(cpn.getAgreement_media_id()) && StringUtils.isNotBlank(cpn.getOperator_media_id())) {
            pramcpn.put("agreement_media_id", cpn.getAgreement_media_id());
            pramcpn.put("operator_media_id", cpn.getOperator_media_id());
        }
        praminfo.put("info", pramcpn);
        log.info("优惠券进件修改提交到微信>>>>>>>>参数:{}", praminfo.toString());
        HttpUriRequest httpUriRequest = RequestBuilder
                .post()
                .setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()))
                .setUri("https://api.weixin.qq.com/card/submerchant/update")
                .addParameter("access_token", API.accessToken(access_token))
                .setEntity(new StringEntity(JSON.toJSONString(praminfo), Charset.forName("utf-8")))
                .build();
        CpnMchIfoResult cpnMchIfoResult = LocalHttpClient.executeJsonResult(httpUriRequest, CpnMchIfoResult.class);
        log.info("优惠券进件修改提交到微信返回参数<<<<<<<:{}", cpnMchIfoResult.toString());

        if (!"0".equals(cpnMchIfoResult.getErrcode())) {
            log.warn("优惠券进件修改提交到微信接口调用失败!!!");
            return ResultMessage.createFail("优惠券进件修改系统繁忙请稍后检查资料后再试!!! errcode:"+cpnMchIfoResult.getErrcode()+"errmsg:"+cpnMchIfoResult.getErrmsg());
        }
        Map resInfo = JSON.parseObject(cpnMchIfoResult.getInfo());
        log.info(cpnMchIfoResult.getInfo());
        String merchant_id = String.valueOf(resInfo.get("merchant_id"));
        String status = String.valueOf(resInfo.get("status"));

        log.info("状态status :{}   merchant_id :{}", status, merchant_id);

        cpn.setMerchant_id(Integer.parseInt(merchant_id));

        cpn.setStatus(1);
        cpn.setReason("审核中");

        if ("CHECKING".equalsIgnoreCase(status)) {
            cpn.setStatus(1);
            cpn.setReason("审核中");
        } else if ("APPROVED".equalsIgnoreCase(status)) {
            cpn.setStatus(2);
            cpn.setReason("已通过");
        } else if ("REJECTED".equalsIgnoreCase(status)) {
            cpn.setStatus(-1);
            cpn.setReason("被驳回");
        } else if ("EXPIRED".equalsIgnoreCase(status)) {
            cpn.setStatus(-1);
            cpn.setReason("协议已过期");
        }
        this.cpnMchInfoDao.update(cpn);
        log.info("优惠券修改进件提交成功 merchant_id :{}", merchant_id);
        return ResultMessage.createSuccess();
    }
}
